﻿using Nemerle;
using Nemerle.Collections;
using Nemerle.Text;
using Nemerle.Utility;
using Nemerle.Imperative;

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;

using Nitra.Declarations;
using Nitra.Serialization2;
using DotNet;

using Ammy.Infrastructure;
using Ammy.Backend;
using Ammy.Symbols;

namespace Ammy.Scopes
{
  public class NamespaceScope : Scope
  {
    public override AllSymbols : Seq[DeclarationSymbol]  { get { _scope.AllSymbols } }
    
    private _scope : Scope;
    private _context : DependentPropertyEvalContext;
    
    public this(scope : Scope, context : DependentPropertyEvalContext)
    {
      _scope = scope;
      _context = context;
    }
        
    public override FindMany[TSymbol](predicate : Predicate[TSymbol], results : ref LightList[TSymbol]) : void
    {
      _scope.FindMany(predicate, ref results)
    }
    
    public override BindMany[TSymbol](reference : Reference, results : ref LightList[TSymbol]) : void
    {
      _scope.BindMany(reference, ref results);
            
      when (results.Count == 0 && _scope is TableScope) {
        def tableScope = _scope :> TableScope;
        
        assert2(tableScope != null);
        
        results.Add(DefaultNamespaceSymbol.Create(reference, tableScope, _context) :> TSymbol)
      }
    }

    public override MakeCompletionList(prefix : string) : Seq[DeclarationSymbol]
    {
      _scope.MakeCompletionList(prefix);
    }
    
    public override ToString() : string
    {
      "NamespaceScope " + _scope
    }

    public override Serialize(writer : BinaryWriter, metadataWriter : MetadataWriter) : void
    {
      metadataWriter.WriteObject(_scope, writer);
    }

    public static Deserialize(reader : BinaryReader, metadataReader : MetadataReader) : this
    {
      def scope = metadataReader.ReadObject.[Scope](reader);
      NamespaceScope(scope, null)
    }
  }
}
